import websocket
import threading
import time

uri = "ws://1.1.1.1:101" #注意替换为自己的ws服务器IP和端口

out_time = 60  # 超时时间


# 接收数据
def on_message(ws, message):
    global out_time
    if message == "pong":
        out_time = 60
    else:
        # '{"device_id": "1234567", "value": 51}'
        print(message)


# 错误事件
def on_error(ws, error):
    print(error)


# 关闭事件
def on_close(ws):
    print("### closed ###")
    time.sleep(1)
    # 尝试重连
    start_connect()


# 成功连接服务器
def on_open(ws):
    global out_time

    def run(*args):
        global out_time
        while 1:
            out_time -= 10
            ws.send("ping")
            time.sleep(10)
            if out_time < 0:
                break
        ws.close()
    # 发心跳线程
    t0 = threading.Thread(target=run)
    t0.setDaemon(True)
    t0.start()
    #ws.send('{"device_id": "1234567"}')


# 连接websocket
def start_connect():
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(uri,
                              on_message=on_message,
                              on_error=on_error,
                              on_close=on_close)
    ws.on_open = on_open
    ws.run_forever()


# 程序入口
if __name__ == "__main__":
    start_connect()
